package com.loong.testretrofitrxjavamvp.api;


import com.le.utils.LogUtils;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author zgq
 * @version 1.0
 * @describe -- 网络请求拦截器
 * @date 2018/5/7
 */
public class TokenInterceptor implements Interceptor {

    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        String bodyString = getBodyString(response);
        LogUtils.e("http_interceptor","拦截器:"+bodyString+":A:"+response.code()
                +":B:"+request.url().toString());

//        if (UtApp.tokenError(bodyString)){
//            response.body().string();
//            return response;
//        }
        return response;
    }


    public String getBodyString(Response response) throws IOException {
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();

        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();

        if (contentType != null) {
            contentType.charset(charset);
        }

        return buffer.clone().readString(charset);
    }


}
